/**
 * @author Teacher Gong
 * @note 登录界面
 */

package team.wh1tegive.cg;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import team.wh1tegive.user.UserAction;
import team.wh1tegive.misc.Log;

class LoginFrame extends JFrame implements ActionListener {
    private JLabel l_user, l_pwd; //用户名标签，密码标签
    private JTextField t_user;//用户名文本框
    private JPasswordField t_pwd; //密码文本框
    private JButton b_ok, b_cancel; //登录按钮，退出按钮

    public LoginFrame() {
        super("金钱管理系统：登录");
        l_user = new JLabel("用户名:", JLabel.RIGHT);
        l_pwd = new JLabel("密码:", JLabel.RIGHT);
        t_user = new JTextField(33);
        t_pwd = new JPasswordField(33);
        b_ok = new JButton("登录");
        b_cancel = new JButton("退出");
        //布局方式FlowLayout，一行排满排下一行
        Container c = this.getContentPane();
        c.setLayout(new FlowLayout());
        c.add(l_user);
        c.add(t_user);
        c.add(l_pwd);
        c.add(t_pwd);
        c.add(b_ok);
        c.add(b_cancel);
        //为按钮添加监听事件
        b_ok.addActionListener(this);
        b_cancel.addActionListener(this);
        //界面大小不可调整
        this.setResizable(false);
        this.setSize(410, 185);

        //界面显示居中
        Dimension screen = this.getToolkit().getScreenSize();
        this.setLocation((screen.width - this.getSize().width) / 2, (screen.height - this.getSize().height) / 2);
        this.setVisible(true);
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                Log.writeLog("Exit Without Logging In.");//点击"×"输出的文字
            }
        });
    }


    public void actionPerformed(ActionEvent e) {
        if (b_cancel == e.getSource()) {
            Log.writeLog("Exit Without Logging In.");
            this.dispose();
            System.exit(0);//添加退出代码
        } else if (b_ok == e.getSource()) {
            //添加代码，验证身份成功后显示主界面
            String uname = t_user.getText();
            String pwd = new String(t_pwd.getPassword());
            if (UserAction.OauthCheck(uname, pwd)) { //登录成功
                Log.writeLog("User " + (uname.equals("") ? "null" : uname) + " Logged In Successfully!");
                this.dispose();
                new MainFrame(t_user.getText().trim());
            } else { //登录失败
                JOptionPane.showMessageDialog(null, "用户名或密码出错", "警告", JOptionPane.ERROR_MESSAGE);
                Log.writeLog("User " + (uname.equals("") ? "null" : uname) + " Logged In Failed.");
                t_pwd.setText("");//密码重置为空串
            }
        }
    }
}
//JOptionPane.showMessageDialog(null,"用户名密码出错", "警告", //JOptionPane.ERROR_MESSAGE);